# -*- coding: utf-8 -*-
import random
from scrapy import Request
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from zc_core.spiders.base import BaseSpider
from zc_core.util.http_util import retry_request
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from cdt.rules import *
from cdt.utils.login import SeleniumLogin


class FullSpider(BaseSpider):
    name = 'full'

    # 常用链接
    item_url = 'http://tang.cdt-ec.com/ny-mall-basedoc/ware/nyGetWareById?token=1561713533643&wareId={}&mall_type=PROPRIETARY&timeTap=1561713537182&orgId=980001780'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        settings = get_project_settings()
        # cookies = SeleniumLogin().get_cookies()
        cookies = {'ucuserid': 'eb50f35e-e9ed-4f16-bdb4-5d02909177d8', 'tenantid': 'nl9dpvts'}
        if not cookies:
            self.logger.error('init cookie failed...')
            return
        self.logger.info('init cookie: %s', cookies)

        pool_list = SkuPoolDao().get_sku_pool_list()
        self.logger.info('全量：%s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            offline_time = sku.get('offlineTime', 0)
            if offline_time > settings.get('MAX_OFFLINE_TIME', 2):
                self.logger.info('忽略: [%s][%s]', sku_id, offline_time)
                continue
            # 避免重复采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: [%s]', sku_id)
                continue
            yield Request(
                url=self.item_url.format(sku_id),
                cookies=cookies,
                callback=self.parse_item_data,
                errback=self.error_back,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                }
            )

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        sku_id = meta.get('skuId')
        data = parse_item_data(response)
        if 'salePrice' in data and data.get('salePrice') > 0:
            self.logger.info('商品: [%s]' % data.get('skuId'))
            yield data
        else:
            self.logger.info('下架: [%s]' % sku_id)
